<template>
  <div class="con">
    <tree @change-video2="changeVideo" class="treeDom" ref="treeDemo"> </tree>
    <router-view to="/Tree" />
    <div class="videoDome">
      <div class="title">
        当前播放视频 > <span style="color: #1ab394">{{ title }}</span>
      </div>

      <video
        id="rtmpVideo"
        ref="video"
        class="videod"
        :class="{ 'full-screen': fullScreen }"
        preload="auto"
        autoplay="true"
        muted="muted"
        poster="@/assets/images/videoLine2.png"
        @dblclick="
          () => {
            this.fullScreen = !this.fullScreen;
          }
        "
      ></video>

      <p class="djs" v-show="isShow">
        {{ ntime == 0 ? "完成" : ntime + "S" }}
      </p>
    </div>
    <div class="kzdome">
      <dd class="lzv">
        <button
          class="el-icon-video-camera-solid"
          @click="recordVideo"
          :disabled="takpicDisable"
        >
          {{ Disables == 1 && takpicDisable ? "录制中..." : "录制" }}
        </button>
        <!-- <select v-model="value">
          <option value="15" checkd>15S</option>
          <option value="20">20S</option>
        </select> -->
      </dd>
      <dd class="lzv">
        <button
          class="iconfont el-icon-zhuapai"
          @click="takpic"
          :disabled="takpicDisable"
        >
          {{ Disables == 2 && takpicDisable ? "抓取中 ..." : "抓取" }}
        </button>
      </dd>
      <dd class="lzv">
        <button
          class="iconfont"
          :class="
            camereDisable && cameraType == 1
              ? 'checked el-icon-under '
              : 'el-icon-bofang'
          "
          @click="taggleCamere(1)"
          :disabled="takpicDisable && cameraType != 1"
        >
          主摄 &nbsp;

          <span style="color: #f0f0f0; font-size: 12px">{{
            cameraType == 1 && camereDisable ? outTime + "自动秒后停止" : ""
          }}</span>
        </button>
      </dd>
      <dd class="lzv">
        <button
          class="iconfont"
          :class="
            camereDisable && cameraType == 2
              ? ' checked el-icon-under'
              : 'el-icon-bofang'
          "
          @click="taggleCamere(2)"
          :disabled="takpicDisable && cameraType != 2"
        >
          副摄 &nbsp;

          <span style="color: #f0f0f0; font-size: 12px">{{
            cameraType == 2 && camereDisable ? outTime + "自动秒后停止" : ""
          }}</span>
        </button>
      </dd>
    </div>
  </div>
</template>

<script>
// import RecordRTC from "recordrtc";
import flvjs from "flv.js";
import Tree from "@/components/tree";
//Recordv
import { Picture, StopVideo, startVideo, Recordv } from "@/http";
export default {
  name: "Video",
  data() {
    return {
      title: "请选择监控设备",
      flvPlayer: null,
      destroy: null,
      recorder: null,
      startTimeCutVideo: null,
      endTImeCutVideo: null,
      value: "15",
      ids: "",
      isShow: false,
      ntime: 15,
      // recordDisable: false,
      Disables: 1, // 1 录像 2 拍照
      fullScreen: false, //是否全屏显示
      camereDisable: false,
      posterSrc: require("../assets/images/loding.gif"), //require("./assets/tx.jpg"),
      interval: null,
      nvrImei: "",
      clearout: null,
      clearinter: null,
      outTime: 60 * 5,
      cameraType: 1, // 主摄 1 副摄 2
      statisticsTiemr: null,
    };
  },
  components: {
    Tree,
  },
  mounted() {},
  computed: {
    takpicDisable() {
      return this.$store.state.Picture;
    },
    videoEnd() {
      return this.$store.state.videoEnd;
    },
  },
  watch: {
    videoEnd(val) {
      val
        ? (() => {
            this.$alert("视频预览结束!", "提示", {
              confirmButtonText: "知道了",
              type: "warning",
            });
            clearTimeout(this.clearout);
            clearInterval(this.clearinter);
            this.camereDisable = false;
          })()
        : "";
    },
  },

  methods: {
    changeVideo(data, dt) {
      this.$refs["treeDemo"].$refs["tree"].setCurrentKey(this.ids);
      if (!data.data.children) {
        console.log(dt);
        if (dt.nvr_state != 0) {
          this.$refs["treeDemo"].$refs["tree"].setCurrentKey(dt.node_id);
          this.title = dt.title;
          if (this.ids !== dt.node_id) {
            this.$store.commit("setPicture", false);
            this.cameraType = 1;
            this.flvPlayer
              ? (() => {
                  this.cutoff2(this.ids);
                  this.ids = dt.node_id;
                  this.nvrImei = dt.nvr_IMEI;
                  this.startVideo();
                })()
              : ((this.ids = dt.node_id),
                (this.nvrImei = dt.nvr_IMEI),
                this.startVideo());
          } else {
            !this.camereDisable && this.startVideo(dt.node_id, dt.nvr_IMEI);
          }
        } else {
          this.$refs["treeDemo"].$refs["tree"].setCurrentKey(this.ids);
          this.$message.warning("当前监控设备不在线!").showClose = true;
        }
      }
    },

    startVideo(nvid = this.ids, IMEI = this.nvrImei, aisle = this.cameraType) {
      // return new Promise(() => {
      startVideo({
        nvr_id: nvid,
        username: localStorage.getItem("username"),
        aisle,
      }).then((res) => {
        res.result_code == 200
          ? (() => {
              this.palyVideo(IMEI);
              this.$store.commit("setVideoEnd", false);
              this.camereDisable = true;
            })()
          : (() => {
              this.$refs.video.poster = "/staic/img/videoLine2.ef9f75cf.png";
              this.$alert(res.data, "提示", {
                confirmButtonText: "知道了",
                type: "warning",
              });
            })();
      });
      // });
    },
    palyVideo(IMEI) {
      if (this.flvPlayer != null) {
        // this.cutoff(this.ids);
      }
      if (flvjs.isSupported()) {
        this.timeoutVideo(300);
        let that = this;
        this.$refs.video.poster = this.posterSrc;

        // RVideo.controls = false;
        this.flvPlayer = flvjs.createPlayer(
          {
            type: "flv",
            cors: true,
            fluid: true,
            hasAudio: false,
            hasVideo: true,
            // duration: 6000,//总媒体持续时间，单位为毫秒
            stashInitialSize: 128, // 减少首桢显示等待时长
            url:
              "http://117.160.141.22:6055/live?port=1935&app=myapp&stream=" +
              IMEI,
          },
          {
            enableStashBuffer: false,
            fixAudioTimestampGap: false,
            isLive: true,
          }
        );

        this.flvPlayer.on(flvjs.Events.LOADING_COMPLETE, () => {
          // console.log("加载完成", res, "MediaSource onSourceEnded");
          this.$alert("视频流已断开!", "提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.flvPlayer.pause();
              this.cutoff2(this.ids);
            },
          });
        });
        // 【重要事件监听】http请求建立好后，该事件会一直监听flvjs实例
        // this.flvPlayer.on(flvjs.Events.STATISTICS_INFO, () => {
        //   // console.log("请求数据信息", res);
        // });

        this.flvPlayer.attachMediaElement(this.$refs.video);
        this.flvPlayer.load();
        this.camereDisable = true;
        setTimeout(() => {
          this.flvPlayer.play();
        }, 200);

        // 销毁事件
        that.destroy = function () {
          this.flvPlayer.pause();
          this.$refs.video.poster = "/staic/img/videoLine2.ef9f75cf.png";
          this.flvPlayer.unload();
          this.flvPlayer.detachMediaElement();
          this.flvPlayer.destroy();
          this.flvPlayer = null;
        };
      } else {
        this.$message.error("浏览器不支持 > 播放失败");
      }
    },

    // 定时关闭
    timeoutVideo(time) {
      this.clearout && clearTimeout(this.clearout);
      this.clearinter && clearInterval(this.clearinter);
      this.outTime = time;
      this.clearout = setTimeout(() => {
        this.cutoff2(this.ids);
        this.$alert("视频预览结束!", "提示", {
          confirmButtonText: "知道了",
          type: "warning",
        });
      }, time * 1000);
      this.clearinter = setInterval(() => {
        --this.outTime;
      }, 1000);
    },
    recordVideo() {
      // 录制视频
      if (this.ids && this.camereDisable) {
        this.$store.commit("setPicture", true);
        this.Disables = 1;
        // this.isShow = true;
        // this.ntime = this.value;
        // this.interval = setInterval(() => {
        //   --this.ntime;
        //   if (this.ntime < 1) {
        //     clearInterval(this.interval);
        //     setTimeout(() => {
        //       this.isShow = false;
        //     }, 1000);
        //   }
        // }, 1000);
        Recordv({
          nvr_id: this.ids,
          userName: localStorage.getItem("username"),
          aisle: this.cameraType,
        })
          .then((res) => {
            console.log(res);
            if (res.result_code == 200) {
              this.$message.success("开始录制!");
              this.$store.commit("setPicture", true);

              setTimeout(() => {
                this.$store.commit("setPicture", false);
              }, 1000 * 60);
            } else {
              this.$store.commit("setPicture", false);
              this.$message.error(res.data);
            }
          })
          .catch((err) => {
            console.log(err);
            this.$store.commit("setPicture", false);
          });
      } else {
        this.$message.warning("请选择在线的可播放的设备!");
      }
    },

    takpic() {
      this.Disables = 2;
      if (this.ids && this.camereDisable) {
        Picture({
          nvr_id: this.ids,
          userName: localStorage.getItem("username"),
          aisle: this.cameraType,
        }).then((res) => {
          if (res.result_code == 200) {
            this.$message.success("设备开始抓取!");
            this.$store.commit("setPicture", true);
            setTimeout(() => {
              this.$store.commit("setPicture", false);
            }, 1000 * 60);
          } else {
            this.$message.warning("抓取中,稍后重试!");
          }
        });
      } else {
        this.$message.warning("请选择在线的可播放的监控设备!");
      }
    },

    //视频断流
    cutoff2(ids) {
      this.clearout && clearTimeout(this.clearout);
      this.clearinter && clearInterval(this.clearinter);
      this.destroy();
      // return new Promise((resolve, reject) => {
      StopVideo({ nvr_id: ids }).then((res) => {
        if (res.result_code == 200) {
          this.camereDisable = false;
          // resolve("断开视频流完成");
        } else {
          this.$message.error(res.data);
          if (res.data == "设备已离线") {
            this.camereDisable = false;
          }
          // reject("断开视频流失败");
        }
      });
      // });
    },
    dbclick() {
      this.fullScreen = !this.fullScreen;
    },
    taggleCamere(value) {
      if (!this.ids) {
        this.$message.warning("请选择监控设备!");
      } else {
        if (this.cameraType == value) {
          this.flvPlayer
            ? ((this.camereDisable = false),
              this.flvPlayer.pause(),
              this.cutoff2(this.ids))
            : this.startVideo();
        } else {
          this.cameraType = value;
          this.flvPlayer
            ? (() => {
                startVideo({
                  nvr_id: this.ids,
                  username: localStorage.getItem("username"),
                  aisle: value,
                }).then((res) => {
                  console.log(res);
                });
              })()
            : this.startVideo();
        }
      }
    },
  },
  activated() {
    if (this.$route.params.id) {
      this.ids = this.$route.params.id;
      this.nvrImei = this.$route.params.imei;
      this.startVideo(this.ids, this.nvrImei);
      this.$refs["treeDemo"].$refs["tree"].setCurrentKey(this.ids);
      this.title = this.$refs["treeDemo"].$refs["tree"].getCurrentNode().title;
    }
  },
  deactivated() {
    this.flvPlayer != null ? this.cutoff2(this.ids) : "";
  },
  destroyed() {
    this.flvPlayer != null ? this.cutoff2(this.ids) : "";
  },
};
</script>

<style lang="less" scoped>
.videod {
  width: 90%;
  position: absolute;
  max-height: 58vh;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.full-screen {
  position: fixed;
  height: auto;
  width: 100vw;
  z-index: 999;
  max-height: 100vh;
}
.con .camre {
  button {
    background: rgb(189, 189, 189);
    padding: 5px 10px;
    color: #333;
    border-radius: 5px;
    // &:nth-child(1) {
    //   border-radius: 8px 0 0 8px;
    // }
    // &:nth-child(2) {
    //   border-radius: 0 8px 8px 0;
    // }
    &:hover {
      opacity: 0.8;
    }
  }
  .activeCarma {
    background: #357ebd;
    color: white;
  }
}
.off {
  .toggle--btn {
    border: 4px solid #1893d1;
    box-shadow: 0 0 10px 0 #22adf3;
    &::before {
      border-color: #1893d1;
    }
    &::after {
      background-color: #1893d1;
    }
  }
}

// .toggle--btn {
//   box-shadow: 0 2px 5px 0px grey, 0 15px 20px 0px transparent;
// }
.toggle--btn {
  position: relative;
  display: inline-block;
  top: 9px;
  left: 5px;
  width: 25px;
  height: 25px;
  background-color: #f9f8f6;
  border: 4px solid #919191;
  border-radius: 50%;
  box-shadow: 0 2px 8px 0px #edeff37d, 0 0 8px 2px transparent;
  &::after,
  &::before {
    content: "";
    display: block;
    position: absolute;
  }
  &::before {
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 45%;
    height: 45%;
    border-radius: 50%;
    border: 2px solid #919191;
    //   box-shadow: inset 0 0 0 5px #aaa, inset 0 0 0 6px #dfdfdf;
  }
  &::after {
    left: 50%;
    top: 30%;
    transform: translate(-50%, -50%);
    width: 2px;
    height: 8px;
    background-color: #a0a0a0;
    box-shadow: 0 0 0 2px #f9f8f6;
  }
}
</style>
